package flc.ast.fragment;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.imgedit.ImgEditActivity;
import com.stark.imgedit.ModuleConfig;
import com.stark.imgedit.utils.Matrix3;
import com.stark.imgedit.view.StickerItem;
import com.stark.imgedit.view.StickerView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import flc.ast.BaseEditFragment;
import flc.ast.R;
import flc.ast.adapter.StickerAdapter;
import flc.ast.bean.MyStickerBean;
import flc.ast.databinding.FragmentStickerBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link StickerFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class StickerFragment extends BaseEditFragment<FragmentStickerBinding> {

    public static final int INDEX = ModuleConfig.INDEX_STICKER;
    public static final String STICKER_FOLDER1 = "stickers/type1";
    public StickerView mStickerView;
    private StickerAdapter stickerAdapter;
    private int oldPosition;

    public static StickerFragment newInstance() {
        StickerFragment fragment = new StickerFragment();
        return fragment;
    }

    @Override
    public void onShow() {
        mImgEditActivity.mode = ImgEditActivity.MODE_STICKERS;
        if (stickerAdapter != null) {
            stickerAdapter.getItem(oldPosition).setSelect(false);
            stickerAdapter.getItem(0).setSelect(true);
            oldPosition = 0;
            stickerAdapter.notifyDataSetChanged();
        }
        mImgEditActivity.mStickerView.setVisibility(View.VISIBLE);
    }

    @Override
    public void backToMain() {
        mImgEditActivity.mode = ImgEditActivity.MODE_NONE;
        mImgEditActivity.mImgView.setVisibility(View.VISIBLE);
        mStickerView.setVisibility(View.GONE);
//        mImgEditActivity.showFunc();
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_sticker;
    }

    @Override
    protected void initView() {
        oldPosition = 0;
        mStickerView = mImgEditActivity.mStickerView;
        LinearLayoutManager stickerListLayoutManager = new LinearLayoutManager(mImgEditActivity);
        stickerListLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        mDataBinding.rvSticker.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        stickerAdapter = new StickerAdapter();
        mDataBinding.rvSticker.setAdapter(stickerAdapter);
        stickerAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        stickerAdapter.getItem(oldPosition).setSelect(false);
        stickerAdapter.getItem(position).setSelect(true);
        oldPosition = position;
        stickerAdapter.notifyDataSetChanged();
        mStickerView.addBitImage(getImageFromAssetsFile(stickerAdapter.getItem(position).getPath()));
    }

    @Override
    protected void initData() {
        try {
            String[] files = mContext.getAssets().list(STICKER_FOLDER1);
            List<MyStickerBean> listSticker = new ArrayList<>();
            for (String file : files) {
                listSticker.add(new MyStickerBean(STICKER_FOLDER1 + File.separator + file, false));
            }
            stickerAdapter.setList(listSticker);
            onShow();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void applyStickers() {
        showDialog(getString(com.stark.common.res.R.string.handling));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                Matrix touchMatrix = mImgEditActivity.mImgView.getImageViewMatrix();

                Bitmap retBitmap = Bitmap.createBitmap(mImgEditActivity.getMainBit()).copy(
                        Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(retBitmap);

                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());

                LinkedHashMap<Integer, StickerItem> addItems = mStickerView.getBank();
                for (Integer id : addItems.keySet()) {
                    StickerItem item = addItems.get(id);
                    item.matrix.postConcat(m);// 乘以底部图片变化矩阵
                    canvas.drawBitmap(item.bitmap, item.matrix, null);
                }

                emitter.onNext(retBitmap);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                if (bitmap != null) {
                    mImgEditActivity.changeMainBitmap(bitmap, true);
                }
                mStickerView.clear();
                backToMain();
            }
        });
    }

    /**
     * 从Assert文件夹中读取位图数据
     *
     * @param fileName
     * @return
     */
    private Bitmap getImageFromAssetsFile(String fileName) {
        Bitmap bitmap = null;
        AssetManager am = getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}